package scatter.portrait.rest.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import scatter.common.rest.validation.DictService;
import scatter.portrait.pojo.user.po.PortraitUser;
import scatter.portrait.rest.PortraitConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import org.springframework.web.bind.annotation.RestController;
import scatter.common.rest.controller.BaseAddUpdateQueryFormController;
import scatter.portrait.pojo.user.po.PortraitUserFeaturesRel;
import scatter.portrait.pojo.user.vo.PortraitUserFeaturesRelVo;
import scatter.portrait.pojo.user.form.PortraitUserFeaturesRelAddForm;
import scatter.portrait.pojo.user.form.PortraitUserFeaturesRelUpdateForm;
import scatter.portrait.pojo.user.form.PortraitUserFeaturesRelPageQueryForm;
import scatter.portrait.pojo.user.form.UserAssignUserFeaturesForm;
import scatter.portrait.pojo.user.form.UserFeaturesAssignUserForm;
import scatter.common.rest.exception.BusinessDataNotFoundException;
import java.util.stream.Collectors;
import scatter.portrait.rest.user.service.IPortraitUserFeaturesRelService;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.Valid;
/**
 * <p>
 * 用户和特征关系表 前端控制器
 * </p>
 *
 * @author yw
 * @since 2021-10-09
 */
@Api(tags = "用户和特征相关接口")
@RestController
@RequestMapping(PortraitConfiguration.CONTROLLER_BASE_PATH + "/user/portrait-user-features-rel")
public class PortraitUserFeaturesRelController extends BaseAddUpdateQueryFormController<PortraitUserFeaturesRel, PortraitUserFeaturesRelVo, PortraitUserFeaturesRelAddForm, PortraitUserFeaturesRelUpdateForm, PortraitUserFeaturesRelPageQueryForm> {
    @Autowired
    private IPortraitUserFeaturesRelService iPortraitUserFeaturesRelService;

    @Autowired
    private DictService dictService;

    @ApiOperation("添加用户和特征")
    @PreAuthorize("hasAuthority('PortraitUserFeaturesRel:add')")
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    @Override
    public PortraitUserFeaturesRelVo add(@RequestBody @Valid PortraitUserFeaturesRelAddForm addForm) {
        // 这里是手动配置
        String idByGroupCodeAndValue = dictService.getIdByGroupCodeAndValue(PortraitUser.FeatureTagSourceGroupCode.feature_tag_source.groupCode(),
                PortraitUser.FeatureTagSourceDictItem.manual.itemValue());
        addForm.setSourceDictId(idByGroupCodeAndValue);
        return super.add(addForm);
    }
    @ApiOperation("根据ID查询用户和特征")
    @PreAuthorize("hasAuthority('PortraitUserFeaturesRel:queryById')")
    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    @Override
    public PortraitUserFeaturesRelVo queryById(@PathVariable String id) {
        return super.queryById(id);
    }

    @ApiOperation("根据ID删除用户和特征")
    @PreAuthorize("hasAuthority('PortraitUserFeaturesRel:deleteById')")
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @Override
    public boolean deleteById(@PathVariable String id) {
        return super.deleteById(id);
    }

    @ApiOperation("根据ID更新用户和特征")
    @PreAuthorize("hasAuthority('PortraitUserFeaturesRel:update')")
    @PutMapping
    @ResponseStatus(HttpStatus.CREATED)
    @Override
    public PortraitUserFeaturesRelVo update(@RequestBody @Valid PortraitUserFeaturesRelUpdateForm updateForm) {
        // 这里是手动配置
        String idByGroupCodeAndValue = dictService.getIdByGroupCodeAndValue(PortraitUser.FeatureTagSourceGroupCode.feature_tag_source.groupCode(),
                PortraitUser.FeatureTagSourceDictItem.manual.itemValue());
        updateForm.setSourceDictId(idByGroupCodeAndValue);
        return super.update(updateForm);
    }

    @ApiOperation("不分页查询用户和特征")
    @PreAuthorize("hasAuthority('PortraitUserFeaturesRel:getList')")
    @GetMapping("/getList")
    @ResponseStatus(HttpStatus.OK)
    @Override
    public List<PortraitUserFeaturesRelVo> getList(PortraitUserFeaturesRelPageQueryForm listPageForm) {
         return super.getList(listPageForm);
    }

    @ApiOperation("分页查询用户和特征")
    @PreAuthorize("hasAuthority('PortraitUserFeaturesRel:getPage')")
    @GetMapping("/getPage")
    @ResponseStatus(HttpStatus.OK)
    @Override
    public IPage<PortraitUserFeaturesRelVo> getPage(PortraitUserFeaturesRelPageQueryForm listPageForm) {
         return super.getPage(listPageForm);
    }

    /**
     * 注意该分配功能会清除已存在的重新添加，会导致标签来源不准确
     * @param cf
     * @return
     */
    @ApiOperation("用户分配特征")
    @PreAuthorize("hasAuthority('PortraitUserFeaturesRel:single:userAssignUserFeatures')")
    @PostMapping("/user/assign/userfeatures")
    @ResponseStatus(HttpStatus.CREATED)
    public Boolean userAssignUserFeatures(@RequestBody @Valid UserAssignUserFeaturesForm cf) {
        // 这里是手动配置
        String idByGroupCodeAndValue = dictService.getIdByGroupCodeAndValue(PortraitUser.FeatureTagSourceGroupCode.feature_tag_source.groupCode(),
                PortraitUser.FeatureTagSourceDictItem.manual.itemValue());
        return iBaseService.removeAndAssignRel(cf.getUserId(),
                cf.getCheckedUserFeaturesIds(),
                cf.getUncheckedUserFeaturesIds(),
                cf.getIsLazyLoad(),
                PortraitUserFeaturesRel::getUserId,
                PortraitUserFeaturesRel::getUserFeaturesId,
                (relDto)->new PortraitUserFeaturesRel().setUserId(relDto.getMainId()).setUserFeaturesId(relDto.getOtherId()).setSourceDictId(idByGroupCodeAndValue));
    }

    @ApiOperation("根据用户ID查询已分配的特征id")
    @PreAuthorize("hasAuthority('PortraitUserFeaturesRel:single:queryByUserId')")
    @GetMapping("/user/{userId}")
    @ResponseStatus(HttpStatus.OK)
    public List<String> queryByUserId(@PathVariable String userId) {
        List<PortraitUserFeaturesRel> rels = iPortraitUserFeaturesRelService.getByUserId(userId);
        if (isEmpty(rels)) {
            throw new BusinessDataNotFoundException("数据不存在");
        }

        return rels.stream().map(item -> item.getUserFeaturesId()).collect(Collectors.toList());
    }

    @ApiOperation("清空用户下的所有特征")
    @PreAuthorize("hasAuthority('PortraitUserFeaturesRel:single:deleteByUserId')")
    @DeleteMapping("/user/{userId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public Boolean deleteByUserId(@PathVariable String userId) {
        return iBaseService.removeAssignRel(userId,PortraitUserFeaturesRel::getUserId);
    }

    /**
     * 注意该分配功能会清除已存在的重新添加，会导致标签来源不准确
     * @param cf
     * @return
     */
    @ApiOperation("特征分配用户")
    @PreAuthorize("hasAuthority('PortraitUserFeaturesRel:single:userFeaturesAssignUser')")
    @PostMapping("/userfeatures/assign/user")
    @ResponseStatus(HttpStatus.CREATED)
    public Boolean userFeaturesAssignUser(@RequestBody @Valid UserFeaturesAssignUserForm cf) {
        // 这里是手动配置
        String idByGroupCodeAndValue = dictService.getIdByGroupCodeAndValue(PortraitUser.FeatureTagSourceGroupCode.feature_tag_source.groupCode(),
                PortraitUser.FeatureTagSourceDictItem.manual.itemValue());
        return iPortraitUserFeaturesRelService.removeAndAssignRel(cf.getUserFeaturesId(),
                cf.getCheckedUserIds(),
                cf.getUncheckedUserIds(),
                cf.getIsLazyLoad(),
                PortraitUserFeaturesRel::getUserFeaturesId,
                PortraitUserFeaturesRel::getUserId,
                (relDto)->new PortraitUserFeaturesRel().setUserFeaturesId(relDto.getMainId()).setUserId(relDto.getOtherId()).setSourceDictId(idByGroupCodeAndValue));
    }

    @ApiOperation("根据特征ID查询已分配的用户id")
    @PreAuthorize("hasAuthority('PortraitUserFeaturesRel:single:queryByUserFeaturesId')")
    @GetMapping("/userfeatures/{userFeaturesId}")
    @ResponseStatus(HttpStatus.OK)
    public List<String> queryByUserFeaturesId(@PathVariable String userFeaturesId) {
        List<PortraitUserFeaturesRel> rels = iPortraitUserFeaturesRelService.getByUserFeaturesId(userFeaturesId);
        if (isEmpty(rels)) {
            throw new BusinessDataNotFoundException("数据不存在");
        }
        return rels.stream().map(item -> item.getUserFeaturesId()).collect(Collectors.toList());
    }

    @ApiOperation("清空特征下的所有用户")
    @PreAuthorize("hasAuthority('PortraitUserFeaturesRel:single:deleteByUserFeaturesId')")
    @DeleteMapping("/userfeatures/{userFeaturesId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public Boolean deleteByUserFeaturesId(@PathVariable String userFeaturesId) {
        return iPortraitUserFeaturesRelService.removeAssignRel(userFeaturesId,PortraitUserFeaturesRel::getUserFeaturesId);
    }
}
